const { remote, ipcRenderer } = require('electron')
let moment = require("moment")
let path = require("path")
let fs = require("fs")
let xlsx = require("node-xlsx")


let openSearchWindow = () => {
    // 创建浏览器窗口
    let win = new remote.BrowserWindow({
        parent: remote.getCurrentWindow(),
        // show: false,
        webPreferences: {
            preload: path.join(__dirname, './search_sdk.js')
        }
    })
    win.webContents.openDevTools()
    // 然后加载应用的 index.html。
    win.loadURL("https://www.hapag-lloyd.com/en/online-business/schedules/interactive-schedule.html")

    win.on("closed", (e) => {
        remote.getCurrentWindow().webContents.send("child-close")
    })

    ipcRenderer.sendSync("save-page", {
        id: win.id,
        data: {}
    })

    return win
}

let buildXLSX = (data, name) => {
    remote.dialog.showSaveDialog({
        //选择操作，此处是打开文件夹
        defaultPath: name + ".xlsx",
        properties: [
            'openFile',
        ],
        //过滤条件
        filters: [
            { name: 'xlsx', extensions: ['xlsx'] },
        ]
    }, function (filename) {
        try {
            fs.writeFileSync(filename, xlsx.build([{ name: name, data: data }]))
            alert("保存成功")
        }
        catch (e) {
            alert(e.message)
        }


    })
}

let getXLSX = (path) => {
    if (path) {
        return Promise.resolve(xlsx.parse(path))
    }
    else {
        return new Promise((resolve) => {
            remote.dialog.showOpenDialog({
                defaultPath: name + ".xlsx",
                properties: [
                    'openFile',
                ],
                //过滤条件
                filters: [
                    { name: 'xlsx', extensions: ['xlsx'] },
                ]
            }, function (path) {
                try {
                    resolve(xlsx.parse(path[0]))
                }
                catch (e) {
                    alert(e.message)
                }
            })
        })
    }
}

let clearStorage = () => {
    return new Promise((resolve) => {
        remote.session.defaultSession.clearStorageData([], (data) => {
            resolve("已清空")
        })
    })
}

let savePage = (winId, method, args) => {
    ipcRenderer.sendSync("save-page", {
        id: winId,
        data: {
            method,
            args
        }
    })
}

window.openSearchWindow = openSearchWindow
window.buildXLSX = buildXLSX
window.getXLSX = getXLSX
window.clearStorage = clearStorage
window.moment = moment
window.savePage = savePage